package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"smartconn.cc/LuoYang/PageFlip"
	"smartconn.cc/LuoYang/SearchEngine"
	"smartconn.cc/tosone/ra_main/coreEvent"
	"smartconn.cc/tosone/ra_main/store"
)

var receiveMsg MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	var m map[string]string
	json.Unmarshal(msg.Payload(), &m)
	switch m["command"] {
	case "bookstart":
		coreEvent.BookStart()
	case "bookstop":
		log.Println("bookstop")
		coreEvent.BookStop()
	case "pageflip":
		coreEvent.Pagevt("")
	case "record":
		log.Println("record")
	case "longpress":
		coreEvent.LongPushHome()
	case "shortpress":
		coreEvent.ShortPushHome(true)
	default:
		log.Println("command " + m["command"] + " is not valid or cannot find command.")
	}
}

func main() {
	if flag := PageFlip.Init(); flag == false {
		log.Println("PageFlip init error.")
		return
	}
	if flag := SearchEngine.Init(); flag == false {
		log.Println("SearchEngine init error.")
		return
	}

	store.ResetStatus()

	mqttOptions := MQTT.NewClientOptions()
	mqttOptions.AddBroker("tcp://127.0.0.1:1883")
	mqttOptions.SetClientID("parsing")
	mqttOptions.SetDefaultPublishHandler(receiveMsg)
	c := MQTT.NewClient(mqttOptions)
	log.Println("Test is running.")
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(-2)
	}
	topic := map[string]byte{
		"ra/command": 0,
	}
	if token := c.SubscribeMultiple(topic, nil); token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		os.Exit(-2)
	}
	signalChannel := make(chan os.Signal, 1)
	signal.Notify(signalChannel, os.Interrupt)
	for {
		select {
		case <-signalChannel:
			return
		}
	}
}
